// src/controllers/patientsController.js
const patientsModel = require('../models/patientsModel');
const tools = require('../utils/tools');

async function getPatients(req, res) {
  try {
    console.log("===========enter getPatients==========");
    // console.log(req.query);
    const page = parseInt(req.query.page) || 1; // 默认第一页
    const limit = parseInt(req.query.limit) || 10; // 默认每页显示10条
    const patients = await patientsModel.getPatients(page,limit); 
    res.json(patients);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
}

async function createPatient(req, res) {
  try {
    const patient = req.body;
    console.log(patient);
    data = tools.generateRandomIdCard(45,1);
    patient.id_number = data.idCard;
    patient.birth_date = data.birthDate;
    // patient.address = data.address;
    patient.phone_number = tools.generatePhoneNumber();

    console.log(patient);

    const id = await patientsModel.createPatient(patient);
    res.status(201).json({ message: 'Patient created successfully', id });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
}

async function updatePatient(req, res) {
  try {
    const { id } = req.params;
    console.log(id);
    const patient = req.body;
    await patientsModel.updatePatient(id, patient);
    res.json({ message: 'Patient updated successfully' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
}

async function deletePatient(req, res) {
  try {
    const { id } = req.params;
    await patientsModel.deletePatient(id);
    res.json({ message: 'Patient deleted successfully' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
}

module.exports = {
  getPatients,
  createPatient,
  updatePatient,
  deletePatient
};